package com.pxl.controller.common;

import com.pxl.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Controller
// 相当于设置全局变量
@SessionAttributes({"username","teaid","stuid"})
public class LoginController {


    @Resource
    private UserService userService;

    /**
     *  登录
     * @return
     */
    @RequestMapping("login")
    public String login() {
        return "login";
    }

    /**
     *  校验用户是学生还是老师
     * @return
     */
    @RequestMapping(value = "check",method = RequestMethod.POST)
    public String checkAccount(@RequestParam("userId") int id, @RequestParam("userPass") String pass, Model model) {
        if(userService.checkAccount(id,pass) == 1) {
            model.addAttribute("stuid",id);
            model.addAttribute("username",userService.getStuNameById(id));
            return "redirect:student/studentIndex";
        } else if(userService.checkAccount(id,pass) == 2) {
            model.addAttribute("teaid",id);
            model.addAttribute("username",userService.getTeaNameById(id));
            return "redirect:teacher/teacherIndex";
        } else {
            model.addAttribute("msg","密码错误!");
            return "login";
        }
    }


    /**
     *  退出,销毁 Session
     * @param request
     * @return
     */
    @RequestMapping("exit")
    public String exit(HttpServletRequest request) {
        request.getSession().invalidate();
        return "login";
    }

}
